const jwt = require("jsonwebtoken");
const { JWT_SECRET,TOKEN_EXPIRES_IN  } = require("../config/config.default");
const { createUser, getUserInfo,updateById } = require("../service/user.service");
const {
  USER_REGISTER_ERROR,
  USER_LOGIN_ERROE,
  PASSWORD_MODIFICATION_FAILED
} = require("../constant/err.type");

class UserController {
  /**
   * 用户注册
   * @param {*} ctx
   * @param {*} next
   */
  async register(ctx, next) {
    try {
      const res = await createUser(ctx.request?.body);
      ctx.body = {
        code: 0,
        msg: "用户注册成功",
        data: {
          id: res.id,
          username: res.username,
        },
      };
    } catch (error) {
      console.error(USER_REGISTER_ERROR.msg, error);
      ctx.app.emit("error", USER_REGISTER_ERROR, ctx);
    }
  }

  /**
   * 用户登录
   * @param {*} ctx
   * @param {*} next
   */
  async login(ctx, next) {
    try {
      const { username } = ctx?.request?.body;
      const { password, ...res } = await getUserInfo({ username });
      ctx.body = {
        code: 0,
        msg: "登录成功",
        data: {
          token: jwt.sign(res, JWT_SECRET, {
            expiresIn: TOKEN_EXPIRES_IN,
          }),
        },
      };
    } catch (error) {
      console.error(USER_LOGIN_ERROE.msg, error);
      ctx.app.emit("error", USER_LOGIN_ERROE, ctx);
      return;
    }
  }

  /**
   * 修改用户密码
   * @param {*} ctx 
   * @param {*} next 
   */
  async changePassword(ctx, next){
    try {
      const id = ctx.state?.user?.id
      const { password } = ctx?.request?.body;
      console.log('id',id)
      console.log('password',password)
      const res = await updateById({id, password})
      if(res){
        ctx.body = {
          code: 0,
          msg: "修改密码成功",
          data: null,
        };
      }else{
        console.error(PASSWORD_MODIFICATION_FAILED.msg, error);
        ctx.app.emit("error", PASSWORD_MODIFICATION_FAILED, ctx);
      }
    } catch (error) {
      console.error(PASSWORD_MODIFICATION_FAILED.msg, error);
      ctx.app.emit("error", PASSWORD_MODIFICATION_FAILED, ctx);
    }
  }
}



module.exports = new UserController();
